import { FC } from 'react';
import { renderToString } from 'react-dom/server';
import { useSelector } from 'umi';
import { Swiper, SwiperSlide } from 'swiper/react/swiper-react';
import { EffectFade, Pagination, Autoplay, Lazy } from 'swiper';
import _ from 'lodash';
import styles from '@/layoutSod/mall_components/Banner/banner.less';
import styles_index from './index.less';
import 'swiper/swiper-bundle.css';
import 'swiper/modules/pagination/pagination.less';
import 'swiper/modules/navigation/navigation.less';
import 'swiper/modules/autoplay/autoplay.less';

const Banner: FC = () => {
  const { banner = [] } = useSelector(
    (state: any) => state['koding/index'].index_data,
  );

  const swiperProps: any = {
    observer: true,
    observeParents: true,
    observeSlideChildren: true,
    onSwiper: (swiper: any) => {
      swiper.slideNext();

      swiper.el.onmouseover = () => {
        swiper.autoplay.stop();
      };
      swiper.el.onmouseout = () => {
        swiper.autoplay.start();
      };
    },
    className: styles.banner,
    loop: true,
    modules: [EffectFade, Pagination, Autoplay, Lazy],
    effect: 'fade',
    autoplay: {
      delay: 2000,
      pauseOnMouseEnter: true,
    },
    pagination: {
      clickable: true,
      bulletClass: styles.pagination_item,
      bulletActiveClass: styles.pagination_item_active,
      renderBullet: (index: number, className: string) => {
        return renderToString(
          <span className={`${className}`}>{banner[index].name}</span>,
        );
      },
    },
    lazy: {
      loadPrevNext: true,
    },
  };

  return (
    <Swiper {...swiperProps}>
      {_.map(banner, (item, key: number) => {
        const obj: any = {
          'data-background': item.image_url,
          href: item.link,
        };
        return (
          <SwiperSlide key={item.id}>
            <a
              {...obj}
              target="_blank"
              className={`${styles_index.a_img} swiper-lazy`}
            >
              <div className="swiper-lazy-preloader"></div>
            </a>
          </SwiperSlide>
        );
      })}
    </Swiper>
  );
};

export default Banner;
